﻿using System;
using System.Net.NetworkInformation;
using log4net;

namespace ShippingManage
{
	public class NetworkHelper
	{
		#region Singleton I
		/// <summary>
		/// Static variable for thread locking
		/// </summary>
		static object SyncRoot = new object();

		/// <summary>
		/// Actual static variable for I
		/// </summary>
		static NetworkHelper mInstance = null;

		/// <summary>
		/// Gets the static instance of this class
		/// </summary>
		public static NetworkHelper I
		{
			get
			{
				if (mInstance == null)
				{
					//initialize new instance
					NetworkHelper tmp = new NetworkHelper();

					//assign to static variable. Lock root for thread-safe locking
					lock (SyncRoot)
					{
						mInstance = tmp;
					}
				}

				return mInstance;
			}
		}
		#endregion

		private readonly ILog _Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

		#region Constructor
		/// <summary>
		/// Default constructor
		/// <para>this constructor is deliberately private so that it cannot be instantiated by anyone else but itself.</para>
		/// </summary>		
		NetworkHelper()
		{
			try
			{
				//register monitor network state
				NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
			}
			catch (Exception ex)
			{
				_Logger.Error("Attach to monitor network state failed", ex);
			}
		}
		#endregion

		#region check network

		bool _IsNetworkAvailable = false;
		public bool IsNetworkAvailable
		{
			get { return _IsNetworkAvailable; }
		}

		void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
		{
			_IsNetworkAvailable = e.IsAvailable;
		}

		bool _CanConnectToServer = false;
		public bool CanConnectToServer
		{
			get
			{
				if (IsNetworkAvailable)
					RefreshConnectToServer();
				return _CanConnectToServer;
			}
		}

		public void RefreshConnectToServer()
		{
			if (!IsNetworkAvailable)
				return;
			//call server service
			try
			{
				ShippingManageServices.ShippingManageService service = new ShippingManageServices.ShippingManageService();
				service.DoWork();
				_CanConnectToServer = true;
			}
			catch (Exception ex)
			{
				_Logger.Error("Try connect to server failed", ex);
				_CanConnectToServer = false;
			}
		}

		#endregion

		~NetworkHelper()
		{
			//unregister monitor network state
			NetworkChange.NetworkAvailabilityChanged -= NetworkChange_NetworkAvailabilityChanged;
		}
	}
}
